//
//  AppDelegate.m
//  BadBoy
//
//  Created by wen on 2017/3/10.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "AppDelegate.h"
#import "BDThirdPartService.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
#import <UserNotifications/UserNotifications.h>
#endif
#import <UMSocialCore/UMSocialCore.h>
#import "AppDelegate+EaseMob.h"
#import "BDCityListHelper.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WXApi.h>
#import "BDUserModel.h"
#import <JMessage/JMessage.h>
#import "BDGuideViewController.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate, WXApiDelegate, JMessageDelegate>
{
    NSString *currentDistrict;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    

        
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self judgeVersion];
    });
    
    
    [JMessage addDelegate:self withConversation:nil];
    
    
    NSString *JMESSAGE_APPKEY = @"bb986081fe24d4a335c708fc";
    NSString *CHANNEL = @"Publish channel";
    
    [JMessage setDebugMode];
    [JMessage setupJMessage:launchOptions
                     appKey:JMESSAGE_APPKEY
                    channel:CHANNEL
           apsForProduction:NO
                   category:nil
             messageRoaming:YES];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JMessage registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                      UIUserNotificationTypeSound |
                                                      UIUserNotificationTypeAlert)
                                          categories:nil];
    } else {
        //categories 必须为nil
        [JMessage registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                      UIRemoteNotificationTypeSound |
                                                      UIRemoteNotificationTypeAlert)
                                          categories:nil];
    }
    
    [self registerJPushStatusNotification];
    
    
    [BDThirdPartService settingThird];
    
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        //监听回调事件
        center.delegate = self;
        //iOS 10 使用以下方法注册，才能得到授权
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                              completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                  // Enable or disable features based on authorization.
                              }];
        
        //获取当前的通知设置，UNNotificationSettings 是只读对象，不能直接修改，只能通过以下方法获取
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            
        }];
    }
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //获取当前版本判断是否需要显示引导页
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:app_Version] boolValue] == NO) {
        BDGuideViewController *guideVC = [[BDGuideViewController alloc] init];
        self.window.rootViewController = guideVC;
        guideVC.finishedGuideBlock = ^{
            BDTabBarViewController *tabbarVC = [[BDTabBarViewController alloc] init];
            self.mainController = tabbarVC;
            self.window.rootViewController = tabbarVC;
        };
    }else{
        BDTabBarViewController *tabbarVC = [[BDTabBarViewController alloc] init];
        self.mainController = tabbarVC;
        self.window.rootViewController = tabbarVC;
    }
    
    //解决iOS11，仅实现heightForHeaderInSection，没有实现viewForHeaderInSection方法时,section间距大的问题
    [UITableView appearance].estimatedRowHeight = 0;
    [UITableView appearance].estimatedSectionHeaderHeight = 0;
    [UITableView appearance].estimatedSectionFooterHeight = 0;
//    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000, 0)
//                                                         forBarMetrics:UIBarMetricsDefault];
    //iOS11 解决SafeArea的问题，同时能解决pop时上级页面scrollView抖动的问题
    if (@available(iOS 11, *)) {
        
//        [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; //iOS11 解决SafeArea的问题，同时能解决
    }
    
    return YES;
}

- (void)registerJPushStatusNotification {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJMSGNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkIsConnecting:)
                          name:kJMSGNetworkIsConnectingNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJMSGNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJMSGNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJMSGNetworkDidLoginNotification
                        object:nil];
    
    [defaultCenter addObserver:self
                      selector:@selector(receivePushMessage:)
                          name:kJMSGNetworkDidReceiveMessageNotification
                        object:nil];
    
}

- (void)networkDidSetup:(NSNotification *)notification {
    BDLog(@"Event - networkDidSetup");
}

- (void)networkIsConnecting:(NSNotification *)notification {
    BDLog(@"Event - networkIsConnecting");
}

- (void)networkDidClose:(NSNotification *)notification {
    BDLog(@"Event - networkDidClose");
}

- (void)networkDidRegister:(NSNotification *)notification {
    BDLog(@"Event - networkDidRegister");
}

- (void)networkDidLogin:(NSNotification *)notification {
    BDLog(@"Event - networkDidLogin");
}

- (void)receivePushMessage:(NSNotification *)notification {
    BDLog(@"Event - receivePushMessage");
    
    NSDictionary *info = notification.userInfo;
    if (info) {
        BDLog(@"The message - %@", info);
    } else {
        BDLog(@"Unexpected - no user info in jpush mesasge");
    }
}

#pragma mark  判断版本和省市数据是否发生了变化
-(void)judgeVersion{
    NSString *url = [NSString stringWithFormat:@"%@tool/statisticsData",KBDBaseURL];
    
    RACCommand *command = [BDNetworkingServer yy_GET:url parameters:nil validation:nil automaticProcessingError:YES];
    RACSignal *signal = [command execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        //获取当前版本判断是否需要显示引导页
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        // app版本
        CGFloat currentVersion = [[infoDictionary objectForKey:@"CFBundleShortVersionString"] floatValue];
        
        //保存控制信息
        CGFloat controlVersion = [x[@"IOS"][@"version"] floatValue];
        BOOL isControl = [x[@"IOS"][@"flag"] boolValue];
        if (controlVersion == currentVersion && isControl) {
            [[NSUserDefaults standardUserDefaults] setObject:@YES forKey:@"versionControl"];
        }else{
            [[NSUserDefaults standardUserDefaults] setObject:@NO forKey:@"versionControl"];
        }
        
        CGFloat maxVersion = [x[@"version"][@"ios_newest_version"] floatValue];
        CGFloat minVersion = [x[@"version"][@"ios_lowest_version"] floatValue];
       
        if (currentVersion < maxVersion) {
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"您的应用不是最新版本，请前往Apple Store进行更新")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
                NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1230003388"];
                [[UIApplication sharedApplication] openURL:url];
                
                if (currentVersion < minVersion) {
                    abort();
                }
            }];
            return;
        }
        
        //district_version 地区表版本
        //先保存允许的城市，然后再请求所有的城市
        NSMutableArray *agreeCityArray = [NSMutableArray array];
        for (NSDictionary *dic in x[@"public_districts"]) {
            [agreeCityArray addObject:dic[@"id"]];
        }
        
        NSString *district_version = x[@"version"][@"district_version"];
        
        [BDCityListHelper judgeCityVersionWithVersion:district_version AgreeCity:agreeCityArray];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {

    }];
}


#if __IPHONE_OS_VERSION_MAX_ALLOWED > 100000
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
        NSString *urlStr = [NSString stringWithFormat:@"%@", url];
        if ([urlStr hasPrefix:@"wx52064d18c1389f26"]) {
            return [WXApi handleOpenURL:url delegate:self];
        }
        if ([url.host isEqualToString:@"safepay"]) {
            // 支付跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                
                /*
                 9000	订单支付成功
                 8000	正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
                 4000	订单支付失败
                 5000	重复请求
                 6001	用户中途取消
                 6002	网络连接出错
                 6004	支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
                 其它	其它支付错误
                 */
                if (self.payResultBlock) {
                    NSInteger stateCode = [resultDic[@"resultStatus"] integerValue];
                    if (stateCode == 9000) {
                        self.payResultBlock(1);
                    }else if (stateCode == 4000) {
                        self.payResultBlock(2);
                    }else if (stateCode == 6001) {
                        self.payResultBlock(3);
                    }
                }
            }];
        }
    }
    return result;
}

#endif

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
        NSString *urlStr = [NSString stringWithFormat:@"%@", url];
        if ([urlStr hasPrefix:@"wx52064d18c1389f26"]) {
            return [WXApi handleOpenURL:url delegate:self];
        }
        if ([url.host isEqualToString:@"safepay"]) {
            // 支付跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//                NSLog(@"result = %@",resultDic);
                if (self.payResultBlock) {
                    NSInteger stateCode = [resultDic[@"resultStatus"] integerValue];
                    if (stateCode == 9000) {
                        self.payResultBlock(1);
                    }else if (stateCode == 4000) {
                        self.payResultBlock(2);
                    }else if (stateCode == 6001) {
                        self.payResultBlock(3);
                    }
                }
            }];
        }
    }
    return result;
}

-(void) onResp:(BaseResp*)resp{
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp*response=(PayResp*)resp;  // 微信终端返回给第三方的关于支付结果的结构体
        if (self.payResultBlock) {
            switch (response.errCode) {
                case WXSuccess:
                {// 支付成功，向后台发送消息
                    self.payResultBlock(1);
                }
                    break;
                case WXErrCodeCommon:
                { //签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                    self.payResultBlock(2);
                }
                    break;
                case WXErrCodeUserCancel:
                { //用户点击取消并返回
                    self.payResultBlock(3);
                }
                    break;
                case WXErrCodeSentFail:
                { //发送失败
                    
                }
                    break;
                case WXErrCodeUnsupport:
                { //微信不支持
                    
                }
                    break;
                case WXErrCodeAuthDeny:
                { //授权失败

                }
                    break;
                default:
                    break;
            }
        }
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if (_mainController) {
        [_mainController jumpToChatList];
    }
    [self easemobApplication:application didReceiveRemoteNotification:userInfo];
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
    [JMessage resetBadge];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    BDLog(@"Action - applicationDidEnterBackground");
    application.applicationIconBadgeNumber = 0;
    [application cancelAllLocalNotifications];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    BDLog(@"Action - applicationWillEnterForeground");
    
    [application cancelAllLocalNotifications];
}
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    BDLog(@"Action - didReceiveRemoteNotification:fetchCompletionHandler:");
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    BDLog(@"Action - didRegisterForRemoteNotificationsWithDeviceToken");
    BDLog(@"Got Device Token - %@", deviceToken);
    
    [JMessage registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    BDLog(@"Action - didFailToRegisterForRemoteNotificationsWithError - %@", error);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    if (_mainController) {
//        [_mainController didReceiveLocalNotification:notification];
    }
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    NSDictionary *userInfo = notification.request.content.userInfo;
    [self easemobApplication:[UIApplication sharedApplication] didReceiveRemoteNotification:userInfo];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    //自身的逻辑
    if (_mainController) {
//        [_mainController didReceiveUserNotification:response.notification];
    }
    //通知本身必须的一句
    completionHandler();
}
#endif


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
